package com.dq.utils;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 日期处理
 * 
 * @author liujiawan
 * @email sunlightcs@gmail.com
 * @date 2018年12月6日 2016年12月21日 下午12:53:33
 */
public class DateUtils  extends org.apache.commons.lang3.time.DateUtils{

	/** 时间格式(yyyy-MM-dd) */
	public final static String DATE_PATTERN = "yyyy-MM-dd";
	/** 时间格式(yyyy-MM-dd HH:mm:ss) */
	public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

    /**
     * 日期格式化 日期格式为：yyyy-MM-dd
     * @param date  日期
     * @return  返回yyyy-MM-dd格式日期
     */
	public static String format(Date date) {
        return format(date, DATE_PATTERN);
    }

    /**
     * 日期格式化 日期格式为：yyyy-MM-dd
     * @param date  日期
     * @param pattern  格式，如：DateUtils.DATE_TIME_PATTERN
     * @return  返回yyyy-MM-dd格式日期
     */
    public static String format(Date date, String pattern) {
        if(date != null){
            SimpleDateFormat df = new SimpleDateFormat(pattern);
            return df.format(date);
        }
        return null;
    }


    /**
     * 根据周数，获取开始日期、结束日期
     * @param week  周期  0本周，-1上周，-2上上周，1下周，2下下周
     * @return  返回date[0]开始日期、date[1]结束日期
     */
    public static Date[] getWeekStartAndEnd(int week) {
        DateTime dateTime = new DateTime();
        LocalDate date = new LocalDate(dateTime.plusWeeks(week));

        date = date.dayOfWeek().withMinimumValue();
        Date beginDate = date.toDate();
        Date endDate = date.plusDays(6).toDate();
        return new Date[]{beginDate, endDate};
    }

    /**
     * 对日期的【秒】进行加/减
     *
     * @param date 日期
     * @param seconds 秒数，负数为减
     * @return 加/减几秒后的日期
     */
    public static Date addDateSeconds(Date date, int seconds) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusSeconds(seconds).toDate();
    }

    /**
     * 对日期的【分钟】进行加/减
     *
     * @param date 日期
     * @param minutes 分钟数，负数为减
     * @return 加/减几分钟后的日期
     */
    public static Date addDateMinutes(Date date, int minutes) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusMinutes(minutes).toDate();
    }

    /**
     * 对日期的【小时】进行加/减
     *
     * @param date 日期
     * @param hours 小时数，负数为减
     * @return 加/减几小时后的日期
     */
    public static Date addDateHours(Date date, int hours) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusHours(hours).toDate();
    }

    /**
     * 对日期的【天】进行加/减
     *
     * @param date 日期
     * @param days 天数，负数为减
     * @return 加/减几天后的日期
     */
    public static Date addDateDays(Date date, int days) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusDays(days).toDate();
    }

    /**
     * 对日期的【周】进行加/减
     *
     * @param date 日期
     * @param weeks 周数，负数为减
     * @return 加/减几周后的日期
     */
    public static Date addDateWeeks(Date date, int weeks) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusWeeks(weeks).toDate();
    }

    /**
     * 对日期的【月】进行加/减
     *
     * @param date 日期
     * @param months 月数，负数为减
     * @return 加/减几月后的日期
     */
    public static Date addDateMonths(Date date, int months) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusMonths(months).toDate();
    }

    /**
     * 对日期的【年】进行加/减
     *
     * @param date 日期
     * @param years 年数，负数为减
     * @return 加/减几年后的日期
     */
    public static Date addDateYears(Date date, int years) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusYears(years).toDate();
    }

    /**
     * 处理时分秒
     */
    public final static SimpleDateFormat SDF_DISPOSE = new SimpleDateFormat("yyyy-MM-dd");
    public final static SimpleDateFormat SDFALL_DISPOSE = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    /**
     * 根据指定时间
     * 获取 年
     * @param date
     * @return
     */
    public static int getYearByDate(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);

        int year = cal.get(Calendar.YEAR);

        return year;
    }
    /**
     * 根据指定时间
     * 获取 月
     * @param date
     * @return
     */
    public static int getMonthByDate(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);

        int month = cal.get(Calendar.MONTH) + 1;

        return month;
    }
    /**
     * 获取指定时间
     * 上一月
     * @param date
     * @return
     */
    public static int getLastMonthByDate(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);

        c.add(Calendar.MONTH, -1);
        int month = c.get(Calendar.MONTH) + 1;
        return month;
    }


    /**
     * 获取指定年月的
     * 第一天
     * @param year
     * @param month
     * @return
     */
    public static Date getFirstDayByYearAndMonth(int year, int month) throws Exception {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);

        //获取某月最小天数
        int firstDay = cal.getMinimum(Calendar.DATE);
        //设置日历中月份的最小天数
        cal.set(Calendar.DAY_OF_MONTH, firstDay);

        Date thisfirstDay = cal.getTime();
        thisfirstDay = SDF_DISPOSE.parse(SDF_DISPOSE.format(thisfirstDay));

        return thisfirstDay;

    }
    /**
     * 获取指定年月的
     * 最后一天
     * @param year
     * @param month
     * @return
     */
    public static Date getLastDayByYearAndMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DATE);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);

        //结束时间  23点59分59秒999毫秒
        cal.set(Calendar.HOUR_OF_DAY,23);
        cal.set(Calendar.MINUTE,59);
        cal.set(Calendar.SECOND,59);
        /// 设置毫秒
//            cal.set(Calendar.MILLISECOND,999);

        Date thislastDay = cal.getTime();

        return thislastDay;

    }

    /**
     * 上周一 日期
     * @param date
     * @return
     */
    public static Date geLastWeekMonday(Date date) throws Exception {
        Calendar cal = Calendar.getInstance();
        cal.setTime(getThisWeekMonday(date));
        cal.add(Calendar.DATE, -7);
        return cal.getTime();
    }
    /**
     * 下周一 日期
     * @param date
     * @return
     */
    public static Date getNextWeekMonday(Date date) throws Exception {
        Calendar cal = Calendar.getInstance();
        cal.setTime(getThisWeekMonday(date));
        cal.add(Calendar.DATE, 7);
        return cal.getTime();
    }

    /**
     * 本周一 日期
     * @param date
     * @return
     */
    public static Date getThisWeekMonday(Date date) throws ParseException {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);

        // 获得当前日期是一个星期的第几天
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
        if (1 == dayWeek) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
        // 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        cal.setFirstDayOfWeek(Calendar.MONDAY);

        // 获得当前日期是一个星期的第几天
        int day = cal.get(Calendar.DAY_OF_WEEK);
        // 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);

        Date thisWeekMonday = cal.getTime();
        thisWeekMonday = SDF_DISPOSE.parse(SDF_DISPOSE.format(thisWeekMonday));

        return thisWeekMonday;
    }

    /**
     * 根据周一 日期
     * 获取周日 日期
     * @param thisWeekMonday
     * @return
     */
    public static Date getThisWeekSunday(Date thisWeekMonday) {
        // 星期日
        Calendar cal = Calendar.getInstance();
        cal.setTime(thisWeekMonday);
        cal.add(Calendar.DATE, 7);
        cal.add(Calendar.SECOND, -1);
        Date thisWeekSunday = cal.getTime();
        return thisWeekSunday;
    }

    /**
     * 获取指定 日期 的前几天/后几天 的 开始 00:00:00
     * 当 参数 dayNum 为0时, 获取的是指定日期的开始
     *
     * @param date 指定日期
     * @param dayNum 推进/后退天数
     * @return
     */
    public static Date getDayBegin(Date date, int dayNum) {
        try {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.DATE, dayNum);
            Date thisWeekMonday = cal.getTime();
            thisWeekMonday = SDF_DISPOSE.parse(SDF_DISPOSE.format(thisWeekMonday));

            return thisWeekMonday;
        }catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取指定 日期 的前几天/后几天 的 end 23:59:59
     * 当 参数 dayNum 为0时, 获取的是指定日期的
     *
     * @param date 指定日期
     * @param dayNum 推进/后退天数
     * @return
     */
    public static Date getDayEnd(Date date, int dayNum) {
        try {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.DATE, dayNum + 1);
            Date thisWeekMonday = cal.getTime();
            thisWeekMonday = SDF_DISPOSE.parse(SDF_DISPOSE.format(thisWeekMonday));

            cal.setTime(thisWeekMonday);
            cal.add(Calendar.SECOND, -1);
            thisWeekMonday = cal.getTime();

            return thisWeekMonday;
        }catch (Exception e) {
            return null;
        }
    }
//TODO    2020年8月5日 10:57:13  @D  注释解决冲突

//    public static final String dateTimeNow(final String format) {
//        return parseDateToStr(format, new Date());
//    }
//    public static final String parseDateToStr(final String format, final Date date) {
//        return new SimpleDateFormat(format).format(date);
//    }
//    public static final Date dateTime(final String format, final String ts) {
//        try {
//            return new SimpleDateFormat(format).parse(ts);
//        } catch (ParseException e) {
//            throw new RuntimeException(e);
//        }
//    }

    public static void main(String[] args) {
        // yyyy-MM-dd HH:mm:ss
        try {
            // 测试星期
            Date date = new Date();
            System.out.println("今天是" + SDFALL_DISPOSE.format(date));
            System.out.println("上周一" + SDFALL_DISPOSE.format(geLastWeekMonday(date)));

            Date thisWeekMonday = getThisWeekMonday(date);
            Date thisWeekSunday = getThisWeekSunday(thisWeekMonday);

            System.out.println("本周一" + SDFALL_DISPOSE.format(thisWeekMonday));
            System.out.println("本周日" + SDFALL_DISPOSE.format(thisWeekSunday));

            System.out.println("下周一" + SDFALL_DISPOSE.format(getNextWeekMonday(date)));


            // 测试月份
            Date firstDayMonth = getFirstDayByYearAndMonth(getYearByDate(date), getMonthByDate(date));
            System.out.println("本月开始" + SDFALL_DISPOSE.format(firstDayMonth));
            Date lastDayMonth = getLastDayByYearAndMonth(getYearByDate(date), getMonthByDate(date));
            System.out.println("本月结束" + SDFALL_DISPOSE.format(lastDayMonth));

            Date firstDayMonthLast = getFirstDayByYearAndMonth(getYearByDate(date), getLastMonthByDate(date));
            System.out.println("上月开始: " + firstDayMonthLast.getTime());
            Date lastDayMonthLast = getLastDayByYearAndMonth(getYearByDate(date), getLastMonthByDate(date));
            System.out.println("上月结束: " + lastDayMonthLast.getTime());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description:  额外添加
     * @param null:
     * @return: null
     * @Author: @Dog_E
     * @Date: 2020/8/5 0005
     **/

    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }
}
